'use client'

import { useEffect, useState, useRef, useCallback } from 'react'

interface CursorTooltipMap {
  [key: string]: string
}

const cursorTooltips: CursorTooltipMap = {
  'goto': '[前往]',
  'initiate': '[启动]',
  'inspect': '[检查]',
  'view': '[查看]',
  'expand': '[展开]',
  'deep-dive': '[深入]',
  'reveal': '[显示]',
  'drag': '[拖拽]',
  'input': '[输入]',
  'select': '[选择]',
  'download': '[下载]',
  'share': '[分享]',
  'contact': '[联系]'
}

export default function CustomCursor() {
  const [tooltip, setTooltip] = useState('')
  const [isVisible, setIsVisible] = useState(false)
  const [isHovering, setIsHovering] = useState(false)
  const [cursorSize, setCursorSize] = useState(8)
  const [isActive, setIsActive] = useState(false)
  const [isMobile, setIsMobile] = useState(false)
  
  const cursorRef = useRef<HTMLDivElement>(null)
  const tooltipRef = useRef<HTMLDivElement>(null)
  const requestRef = useRef<number>()
  const targetPosition = useRef({ x: 0, y: 0 })
  const currentPosition = useRef({ x: 0, y: 0 })
  const targetTooltipPosition = useRef({ x: 0, y: 0 })
  const currentTooltipPosition = useRef({ x: 0, y: 0 })

  // 检测移动设备
  useEffect(() => {
    const checkMobile = () => {
      setIsMobile(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))
    }
    checkMobile()
  }, [])

  // 高性能动画函数
  const animateCursor = useCallback(() => {
    if (!cursorRef.current) return

    // 鼠标主体动画 - 使用更高的缓动系数获得更流畅的跟随
    const dx = targetPosition.current.x - currentPosition.current.x
    const dy = targetPosition.current.y - currentPosition.current.y
    
    currentPosition.current.x += dx * 0.35 // 提高缓动系数
    currentPosition.current.y += dy * 0.35
    
    // 使用 transform3d 启用硬件加速
    cursorRef.current.style.transform = `translate3d(${currentPosition.current.x}px, ${currentPosition.current.y}px, 0)`

    // 工具提示动画 - 稍微延迟跟随产生层次感
    if (tooltipRef.current && isVisible) {
      const tooltipDx = targetTooltipPosition.current.x - currentTooltipPosition.current.x
      const tooltipDy = targetTooltipPosition.current.y - currentTooltipPosition.current.y
      
      currentTooltipPosition.current.x += tooltipDx * 0.25
      currentTooltipPosition.current.y += tooltipDy * 0.25
      
      tooltipRef.current.style.transform = `translate3d(${currentTooltipPosition.current.x}px, ${currentTooltipPosition.current.y}px, 0)`
    }
    
    requestRef.current = requestAnimationFrame(animateCursor)
  }, [isVisible])

  useEffect(() => {
    // 移动设备不显示自定义鼠标
    if (isMobile || typeof window === 'undefined') return

    // 添加隐藏光标的样式
    document.body.classList.add('cursor-hidden')

    const updateCursor = (e: MouseEvent) => {
      targetPosition.current = { x: e.clientX, y: e.clientY }
      targetTooltipPosition.current = { x: e.clientX + 20, y: e.clientY - 12 }
      
      // 首次移动时立即设置位置，避免从原点开始动画
      if (currentPosition.current.x === 0 && currentPosition.current.y === 0) {
        currentPosition.current = { x: e.clientX, y: e.clientY }
        currentTooltipPosition.current = { x: e.clientX + 20, y: e.clientY - 12 }
      }
    }

    const handleMouseEnter = (e: Event) => {
      const target = e.target as HTMLElement
      const cursorType = target.getAttribute('data-cursor-text')
      const isClickable = target.tagName === 'A' || target.tagName === 'BUTTON' || target.getAttribute('role') === 'button'
      
      setIsHovering(true)
      
      if (cursorType && cursorTooltips[cursorType]) {
        setTooltip(cursorTooltips[cursorType])
        setIsVisible(true)
      }
      
      // 根据元素类型调整鼠标大小
      if (isClickable) {
        setCursorSize(16)
      } else {
        setCursorSize(12)
      }
    }

    const handleMouseLeave = () => {
      setTooltip('')
      setIsVisible(false)
      setIsHovering(false)
      setCursorSize(8)
    }

    const handleMouseDown = () => {
      setIsActive(true)
      setCursorSize(6)
    }

    const handleMouseUp = () => {
      setIsActive(false)
      setCursorSize(isHovering ? 16 : 8)
    }

    // 鼠标离开/进入窗口检测
    const handleMouseLeaveWindow = () => {
      if (cursorRef.current) {
        cursorRef.current.style.opacity = '0'
      }
    }

    const handleMouseEnterWindow = () => {
      if (cursorRef.current) {
        cursorRef.current.style.opacity = '1'
      }
    }

    // 添加事件监听
    document.addEventListener('mousemove', updateCursor, { passive: true })
    document.addEventListener('mousedown', handleMouseDown, { passive: true })
    document.addEventListener('mouseup', handleMouseUp, { passive: true })
    document.addEventListener('mouseleave', handleMouseLeaveWindow, { passive: true })
    document.addEventListener('mouseenter', handleMouseEnterWindow, { passive: true })

    // 为所有有 data-cursor-text 属性的元素添加事件监听
    const elementsWithCursor = document.querySelectorAll('[data-cursor-text]')
    elementsWithCursor.forEach(element => {
      element.addEventListener('mouseenter', handleMouseEnter, { passive: true })
      element.addEventListener('mouseleave', handleMouseLeave, { passive: true })
    })

    // 为链接、按钮等添加默认属性
    const links = document.querySelectorAll('a:not([data-cursor-text])')
    const buttons = document.querySelectorAll('button:not([data-cursor-text])')
    const inputs = document.querySelectorAll('input:not([data-cursor-text]), textarea:not([data-cursor-text])')

    links.forEach(link => {
      if (!link.getAttribute('data-cursor-text')) {
        link.setAttribute('data-cursor-text', 'goto')
        link.addEventListener('mouseenter', handleMouseEnter, { passive: true })
        link.addEventListener('mouseleave', handleMouseLeave, { passive: true })
      }
    })

    buttons.forEach(button => {
      if (!button.getAttribute('data-cursor-text')) {
        button.setAttribute('data-cursor-text', 'initiate')
        button.addEventListener('mouseenter', handleMouseEnter, { passive: true })
        button.addEventListener('mouseleave', handleMouseLeave, { passive: true })
      }
    })

    inputs.forEach(input => {
      if (!input.getAttribute('data-cursor-text')) {
        input.setAttribute('data-cursor-text', 'input')
        input.addEventListener('mouseenter', handleMouseEnter, { passive: true })
        input.addEventListener('mouseleave', handleMouseLeave, { passive: true })
      }
    })

    // 启动动画循环
    requestRef.current = requestAnimationFrame(animateCursor)

    return () => {
      // 清理
      document.body.classList.remove('cursor-hidden')
      
      if (requestRef.current) {
        cancelAnimationFrame(requestRef.current)
      }
      
      document.removeEventListener('mousemove', updateCursor)
      document.removeEventListener('mousedown', handleMouseDown)
      document.removeEventListener('mouseup', handleMouseUp)
      document.removeEventListener('mouseleave', handleMouseLeaveWindow)
      document.removeEventListener('mouseenter', handleMouseEnterWindow)
      
      elementsWithCursor.forEach(element => {
        element.removeEventListener('mouseenter', handleMouseEnter)
        element.removeEventListener('mouseleave', handleMouseLeave)
      })
      links.forEach(link => {
        link.removeEventListener('mouseenter', handleMouseEnter)
        link.removeEventListener('mouseleave', handleMouseLeave)
      })
      buttons.forEach(button => {
        button.removeEventListener('mouseenter', handleMouseEnter)
        button.removeEventListener('mouseleave', handleMouseLeave)
      })
      inputs.forEach(input => {
        input.removeEventListener('mouseenter', handleMouseEnter)
        input.removeEventListener('mouseleave', handleMouseLeave)
      })
    }
  }, [animateCursor, isHovering, isMobile])

  // 移动设备不渲染自定义鼠标
  if (isMobile) return null

  return (
    <>
      <div
        ref={cursorRef}
        className={`custom-cursor ${isHovering ? 'hovering' : ''} ${isActive ? 'active' : ''}`}
        style={{
          width: `${cursorSize}px`,
          height: `${cursorSize}px`,
        }}
      />
      {tooltip && (
        <div
          ref={tooltipRef}
          className={`cursor-tooltip ${isVisible ? 'visible' : ''}`}
        >
          {tooltip}
        </div>
      )}
    </>
  )
} 